/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/*************************************************************************
 * File: json_cfg.cpp
 *************************************************************************
 *\author: starlove
 *************************************************************************/

#include <tools/json_cfg.h>

CJsonConfigParser::CJsonConfigParser()
:m_pSection(NULL)
{

}

bool CJsonConfigParser::LoadFromFile(const char *path)
{
	char szFileBuf[10240];
	FILE *f = fopen(path, "rb");
	if(!f)
		return false;
	if( fread(szFileBuf, 10240, 1, f) != 0 )
	{
		fclose(f);
		return false;
	}
	fclose(f);
	CJsonCodec cjc;
	char szTempBuf[__BUFFER_SIZE__];
	BUFFER_WRAPPER buff;
	buff.init(szTempBuf, __BUFFER_SIZE__);
	IEncoder *pEncoder = cjc.GetEncoder();
	JSON_BUFFER json_buff = {szFileBuf, szFileBuf + strlen(szFileBuf)};
	pEncoder->Encode(&buff, &json_buff);
	m_ConfigMain.Load(&buff);
	return true;
}

bool CJsonConfigParser::EnterSection(const char *szSectionName)
{
	m_pSection = m_ConfigMain.GetObjectRef<ENCODESTR, CMapData>(szSectionName);
	if(!m_pSection)
		return false;
	return true;
}

int CJsonConfigParser::GetIntValue(const char *szKey, int def = 0)
{
	if(!m_pSection)
		return def;
	return m_pSection->GetNumber<ENCODESTR,int>(szKey, def);
}

const char *CJsonConfigParser::GetStrValue(const char *szKey, const char *def = "")
{
	if(!m_pSection)
		return def;
	return m_pSection->GetString<ENCODESTR>(szKey, def);
}
